!function($) {
  var app = {
    now: '',
    userId: '',
    prizeId: '',

    init: function() {
      $('input').attr('disabled', true);

      document.addEventListener("WeixinJSBridgeReady", function () {
        document.getElementById('bg-music').play();
      }, false);

      this.wxInit();
      var that = this;
      wx.ready(function() {
        that.share(that);
        wx.checkJsApi({
          jsApiList: [
            'chooseImage',
            'uploadImage',
            'getLocalImgData',
            'downloadImage'
          ]
        });
      })

      this.goPage('finger');
      this.initEvent();
      this.initPageRule();
      this.initPageFinger();
      this.initPageEnter();
      this.initPageShake();
      this.initPageThanks();
      this.initPageWin();
      this.initPageShare();
      this.initPageCreate();
    },

    initEvent: function() {
      var that = this;
      $('.rule-btn').on('click', function() {
        that.showPageRule();
      });

      $('.back-btn').on('click', function() {
        that.goPage('create')
      });

      $('.share-btn').on('click', function() {
        that.showPageShare();
      });

      $('.share-page').on('click', function() {
        that.hidePageShare();
      });
    },

    initPageRule: function() {
      var that = this;
      $('.page-rule').on('click', '.close, .start-btn', function(e) {
        e.preventDefault();
        that.hidePageRule();
      });
    },

    showPageShare: function() {
      $('.share-page').addClass('on')
    },

    hidePageShare: function() {
      $('.share-page').addClass('on')
    },

    showPageRule: function() {
      $('.page-rule').addClass('on')
    },

    hidePageRule: function() {
      $('.page-rule').removeClass('on')
    },

    initSound: function() {
      var audio = document.getElementById("shake-sound");
      audio.play();
      audio.setAttribute('src', 'http://xunda.moredesignstudio.cn/app_h5/tpl/images/shake.mp3');
      audio.load();
    },

    initPageFinger: function() {
      // var timeId = null;
      // var num = 0;
      var that = this;

      $('.page-finger')
        .on('click', function(e) {
          e.preventDefault();
          that.initSound();
          that.showPageRule();
          setTimeout(function() {
            that.goPage('enter');
          }, 600);
          // timeId = setInterval(function() {
          //   num += 100
          //   if(num >= 1000) {
          //
          //     clearInterval(timeId);
          //   }
          // }, 100)
        })
        // .on('touchend', function() {
        //   clearInterval(timeId);
        // })
    },

    initPageEnter: function() {
      var that = this;

      $('.create-btn').on('click', function() {
        var src = $('.page-enter .upload-image').css('background-image');
        if(!src || src == 'none') {
          alert('请选择图片上传');
          return;
        } else if(!$('.enter-city').text()) {
          alert('请输入城市');
          return;
        }
        $('#generate-upload-img').css('background-image', src);
        $('#generate-city-text').html($('.enter-city').html());
        that.initId();
      });

      $('#city').on('blur', function() {
        $('.page-enter .generate-city').html($('#city').val());
      });

      $('.upload-input').on('click', function() {
        wx.chooseImage({  
          count: 1,  
          needResult: 1,  
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有  
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
          success: function (data) {                  
            localIds = data.localIds[0];   // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            that.wxgetLocalImgData(localIds, that);
          }   
        });
        // var file = this.files[0];

        // if(!file) return;

        // var ex = file.name.toLowerCase().split('.').splice(-1)[0];
        // var allowEx = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'];

        // if(allowEx.indexOf(ex) < 0 ) {
        //   alert('请选择图片上传');
        //   return;
        // } else if(that.getFileSize(file) > 3) {
        //   alert('请选择少于3MB的图片');
        //   return;
        // }

        // that.readFile(file);
      });
    },

    wxgetLocalImgData: function(e, that){
      var $myimg = $('.page-enter .upload-image');    
      if(window.__wxjs_is_wkwebview){
       wx.getLocalImgData({
          localId: e, // 图片的localID
          success: function (res) {
            var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
              localData = localData.replace('jgp', 'jpeg');//iOS 系统里面得到的数据，类型为 image/jgp,因此需要替换一下                                            
              $myimg.css('background-image', 'url(' + localData + ')')
          },fail:function(res){
            alert("显示失败");
          }
       });
      }else{
        var bgi = '';
        wx.getLocalImgData({
          localId: e, // 图片的localID
          success: function (res) {
            // alert(res.localData);
            var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
            localData.replace(/[\r\n]/g, "").replace(/\ +/g, "").replace(/[ ]/g, "");
            that.uploadGenerateImg('data:image/png;base64,' + localData).done(function(data) {
              $myimg.css('background-image', 'url(/'+data.data.img_url+')');
            })
            // bgi = 'url(data:image/jpeg;base64,' + localData + ')';
            // $myimg.css('background-image', bgi);
            // alert($myimg.css('background-image'));
            // setTimeout(function() {
            //   $myimg.css('background-image', bgi);
            //   alert($myimg.css('background-image');
            // }, 0);
            // alert(bgi)
          },fail:function(res){
            alert("显示失败");
          }
        });

        // setTimeout(function() {
        //   $myimg.css('background-image', bgi);
        // }, 1000)

        // alert(e);
        // $('#upload').val(e);
        // alert($('#upload')[0].value)
        // alert($('#upload')[0].files)
        // $myimg.css('background-image', 'url(' + e + ')');
      }
    },

    share: function(that) {
      var share = {
        title: '迅达厨电邀你见证',
        desc: '“平板灶 迅达造” 暨平板灶新品发布会，期待您的到来',
        link: location.href,
        imgUrl: 'http://xunda.moredesignstudio.cn/app_h5/tpl/images/icon.jpg'
      };
      wx.onMenuShareQQ(share);
      wx.onMenuShareTimeline(share);
      wx.onMenuShareAppMessage(share);
    },

    wxInit: function() {
      var url = encodeURIComponent(location.href);

      $.ajax({
        type: "get",
        url: "/wx/jssdk.php?url=" + url
      }).done(function(data) {
        var wxData = JSON.parse(data)
        wx.config({
          debug: false,
          appId: wxData.appId,
          timestamp: wxData.timestamp,
          nonceStr: wxData.nonceStr,
          signature: wxData.signature,
          jsApiList: [
            "onMenuShareTimeline", //分享给好友
            "onMenuShareAppMessage", //分享到朋友圈
            "onMenuShareQQ", //分享到QQ
            "onMenuShareWeibo", //分享到微博
            'chooseImage','uploadImage','getLocalImgData','downloadImage'
          ]
        });
      })
    },

    initPageShake: function() {
      var that = this;

      $('.page-shake').on('click', function() {
        that.getGift();
      })

      var shake = new Shake(1000, function(obj) {
        if (app.now == "page-shake") {
          that.autoPlayAudio();
          setTimeout(function() {
            that.getGift();
          }, 700);
        }
      });
      shake.init();
    },

    initPageThanks: function() {

    },

    initPageCreate: function() {
      var that = this;
      $('.fuli-btn').on('click', function() {
        if(that.prizeId == '') {
          that.goPage('shake');
        } else if (that.prizeId == 1) {
          that.goPage('thanks');
        } else {
          that.goPage('success');
        }
      })
    },

    initPageWin: function() {
      var that = this;
      $('.page-win .confirm-btn').on('click', function() {
        if(!$('#name').val()) {
          alert('请输入姓名');
          return;
        }
        else if(!$('#phone').val()) {
          alert('请输入电话');
          return;
        }
        if(!$('#address').val()) {
          alert('请输入地址');
          return;
        }
        that.submitInfo();
      })
    },

    initPageShare: function() {
      $('.share-page').on('click', function() {
        $('.share-page').removeClass('on')
      })
    },

    getGift: function() {
      var that = this;

      $.ajax({
        url: '/app_h5/index.php?t=t',
        type: 'POST',
        dataType: 'json',
        data: {
          c: 'api',
          a: 'lottery'
        },
      })
      .done(function(data) {
        that.prizeId = data.data.prize.id;
        if(that.prizeId == 1) {
          that.goPage('thanks');
        } else {
          that.goPage('win');
        }
      });
    },

    goPage: function(name) {
      this.now = 'page-' + name;

      $('.page.on').not('.page-rule')
        .removeClass('on')
        .find('input').attr({disabled: true});

      $('.' + this.now)
        .addClass('on')
        .find('input').attr({disabled: false});
    },


    autoPlayAudio: function () {
      document.getElementById('shake-sound').play();
    },

    generateImg: function() {
      var that = this;

      html2canvas(document.querySelector("#generate"), {
        onrendered: function(canvas) {
        },
        width: $("#generate").width(),
        height: $("#generate").height()
      }).then(function(canvas) {
        var imgData = canvas.toDataURL("image/png");
        $('#page-create-img').attr('src', imgData);
        that.goPage('create');
        that.uploadGenerateImg(imgData)
      });
    },

    // readFile: function(f){
    //   var reader = new FileReader();
    //   reader.readAsDataURL(f);
    //   reader.onload = function(){
    //     var imgData = reader.result;
    //     $('.page-enter .upload-image img').attr('src', imgData)
    //     $('.page-enter .upload-image')
    //       .css('background-image', 'url(' + imgData + ')')
    //       .css('z-index', 999)
    //   }
    //   reader.onerror = function(e){
    //     alert("请选择图片上传");
    //   }
    // },

    getFileSize: function(f) {
      try {
        var size = 0;
        size = f.size;//byte
        size = size / 1024;//kb
        size = size / 1024;//mb
        return size;
      } catch (e) {
        alert("错误：" + e);
        return -1;
      }
    },

    submitInfo: function() {
      var that = this;

      $.ajax({
        url: '/app_h5/index.php?t=t',
        type: 'POST',
        dataType: 'json',
        data: {
          c: 'api',
          a: 'feedback',
          contact: $('#name').val(),
          phone: $('#phone').val(),
          address: $('#address').val(),
          prize: that.prizeId
        }
      })
      .done(function(data) {
        if(data.code != '200'){
          alert(data.msg);
          return;
        }

        that.goPage('success');
      });
    },

    initId: function() {
      var that = this;

      $.ajax({
        url: '/app_h5/index.php?t=t',
        type: 'POST',
        dataType: 'json',
        data: {
          c: 'api',
          a: 'initUser'
        }
      })
      .done(function(data) {
        that.userId = data.data.user_id;
        $('#user-id').html('见证者ID：第' + that.userId + '号');
        setTimeout(function() {
          that.generateImg();
        }, 700)
      })
    },

    uploadGenerateImg: function(imgData) {
      return $.ajax({
        url: '/app_h5/index.php?t=t',
        type: 'POST',
        dataType: 'json',
        data: {
          a: 'upload_full',
          c: 'api',
          img: imgData
        }
      })
      // .done(function(data) {
      //   console.log("success");
      // })
      // .fail(function() {
      //   alert('请求失败，请您稍后再试');
      // });
    }
  };

  $(function() {
    app.init();
  })
}(jQuery);